package cn.edu.hit.kg.file;

import cn.edu.hit.kg.Neo4jConfigurationUtil;
import cn.edu.hit.kg.data.GraphDataProvider;
import cn.edu.hit.kg.data.Node;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class FileDataProvider implements GraphDataProvider {
    private Map<Long, NodeImpl> nodes = null;
    private Map<Long, Set<Long>> edges = null;
    private Map<String, Set<Long>> labelGroups = null;

    private Map configure = null;

    static ObjectMapper objectMapper = new ObjectMapper();

    private void setValue() {
        try {
            InputStream inputStream;  //更改
            String graphPath = (String) configure.getOrDefault("graphPath","graph.json");
            if ((boolean)configure.getOrDefault("graphInClassPath", true)){
                inputStream = Neo4jConfigurationUtil.openFileStream(graphPath);
            }
            else {
                inputStream = Files.newInputStream(Paths.get(graphPath));
            }
            FileDataProvider data = objectMapper.readValue(inputStream, FileDataProvider.class);
            this.edges = data.edges;
            this.labelGroups = data.labelGroups;
            this.nodes = data.nodes;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Map<Long, Node> getNodes() {
        if (nodes == null) {
            setValue();
        }
        Map<Long, Node> nodeMap = new HashMap<>();
        nodeMap.putAll(nodes);
        return nodeMap;
    }

    @Override
    public Map<Long, Set<Long>> getEdges() {
        if (edges == null) {
            setValue();
        }
        return edges;
    }

    @Override
    public Map<String, Set<Long>> getLabelGroups() {
        if (labelGroups == null) {
            setValue();
        }
        return labelGroups;
    }

    @Override
    public boolean config(Map configure) {
        this.configure = configure;
        return !Boolean.parseBoolean(configure.getOrDefault("useNeo4j", false).toString());
    }
}
